/**
 * 工具类
 * @author tao
 */

/**
 * 函数防抖
 * @param {callback} fn 事件回调
 * @param {number} delay 每次推迟执行的等待时间
 * Eg:
 *    函数名:debounce(function(){
 *      console.log("函数输出");
 *    },1000)
 */
export const debounce = function (fn: Function, delay: number) {
  let timer: number | undefined;
  return function (args: any) {
    const _args = args
    clearTimeout(timer)
    timer = window.setTimeout(() => {
      fn.call(this, _args)
    }, delay)
  }
};

/**
 * 函数节流
 * @param {*} fn 事件回调 
 * @param {*} interval 时间间隔的阈值
 * Eg:
 *    函数名:throttle(function(){
 *      console.log("函数输出");
 *    },1000)
 */
export const throttle = function (fn: Function, interval: number) {
  let last: number = 0;
  return function () {
    const context = this;
    const args = arguments;
    const now = +new Date();

    if (now - last >= interval) {
      last = now;
      fn.apply(context, args);
    }
  };
};

export default {
  debounce,
  throttle,
};
